package com.starsea.book.ui.newpage.adapter

import android.content.Context
import android.text.TextUtils
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import com.starsea.book.R
import com.starsea.book.base.adapter.ItemViewHolder
import com.starsea.book.base.adapter.RecyclerAdapter
import com.starsea.book.databinding.ItemHomeBookListBinding
import com.starsea.book.ui.newpage.entity.HomeDataEntity
import com.starsea.book.ui.newpage.utils.KeywordUtil
import com.starsea.book.ui.newpage.utils.loadNormalImage
import com.starsea.book.ui.widget.recycler.ItemTouchCallback

class HomeAdapter(
    var mContext: Context,
    var type: Int = 0,
    var onChanged: ((value: HomeDataEntity) -> Unit)? = null
) :
    RecyclerAdapter<HomeDataEntity, ItemHomeBookListBinding>(mContext),
    ItemTouchCallback.Callback {

    var keyWord: String = ""

    override fun getViewBinding(parent: ViewGroup): ItemHomeBookListBinding {
        return ItemHomeBookListBinding.inflate(inflater, parent, false)
    }

    override fun registerListener(holder: ItemViewHolder, binding: ItemHomeBookListBinding) {
        binding.root.setOnClickListener {
            getItem(if (type == 1) holder.layoutPosition else holder.layoutPosition - 1)?.let {
                onChanged!!.invoke(it)
            }

        }
    }

    override fun convert(
        holder: ItemViewHolder,
        binding: ItemHomeBookListBinding,
        item: HomeDataEntity,
        payloads: MutableList<Any>
    ) {
        binding.run {

//                root.setBackgroundColor(ColorUtils.withAlpha(context.backgroundColor, 0.5f))
            ivCover.loadNormalImage(mContext, item.bookCover)

            if (TextUtils.isEmpty(keyWord)) {
                tvBookName.text = item.bookTitle
                tvBookDesc.text = item.bookDesc
            } else {

                tvBookName.text = KeywordUtil.matchSearchTitle(
                    ContextCompat.getColor(mContext, R.color.highlight),
                    item.bookTitle,
                    keyWord
                )

                tvBookDesc.text = KeywordUtil.matchSearchTitle(
                    ContextCompat.getColor(mContext, R.color.highlight),
                    item.bookDesc,
                    keyWord
                )


            }


        }
    }


}